import { UserRole } from '@/types/enum';
import { removeToken } from '@/utils';
import { masterInfo } from '@/store/modules/master';
import { serviceInfo } from '@/store/modules/service';
import store from '@/store';

/**
 * 比较应用程序的版本号大小
 * @param {string} latestVersion 线上最新版本号
 * @return {boolean}
*/
function compareVersion(latestVersion: string): boolean {
		// 当前系统版本
		const currentVersion = getSystemVersion();
    const version1 = latestVersion.split('.'); // 将线上最新版本号分割成数组
    const version2 = currentVersion.split('.'); // 将当前系统版本号分割成数组
    
    for (let i = 0; i < Math.max(version1.length, version2.length); i++) {
			const num1 = parseInt(version1[i] || '0', 10); // 获取当前位置上的数值并转换为整数类型
			const num2 = parseInt(version2[i] || '0', 10);
			
			if (num1 > num2) {
				return true; // 返回true表示线上版本大于当前版本
			} else if (num1 < num2) {
				return false;
			}
    }
    
    return false; // 返回false表示两个版本号相同或者没有进行比较
}

// 获取当前应用程序的版本号
const getSystemVersion = (): string => {
	const systemInfo = uni.getSystemInfoSync();
	return systemInfo.appVersion;
};

//图片地址转base64格式
function imgToBase64(url: string, cb: (url: string) => void){
	var canvas = document.createElement('canvas'),
		ctx = canvas.getContext('2d'),
	img = new Image;
	
	img.crossOrigin = 'Anonymous';
	img.onload = function () {
		canvas.height = img.height;
		canvas.width = img.width;
		ctx.drawImage(img, 0, 0);
		var dataURL = canvas.toDataURL('image/png');
		cb && cb(dataURL);
		canvas = null;
	};
	img.src = url;
};

// base64转file
function base64ToFile(base64: string, name: string) {
	if (typeof base64 != 'string') {
		return;
	}
	const arr = base64.split(',')
	const type = arr[0].match(/:(.*?);/)[1]
	const fileExt = type.split('/')[1]
	const bstr = atob(arr[1])
	let n = bstr.length
	const u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], `${name}.` + fileExt, {
		type: type,
	});
}

// 获取节点信息
function getSelectorData(selector: string): Promise<any> {
	return new Promise(resolve => {
		uni.createSelectorQuery().select(selector).boundingClientRect(data => {
			resolve(data);
		}).exec()
	});
}

/* 节流 */
function throttle <T extends (...args: any[]) => any>(func: T, delay: number): T {  
  let lastCall = 0;  
  let context: any;  
  let args: any[];  
  
  return function throttledFunction(...functionArgs: any[]) {  
    const now = Date.now();  
    if (now - lastCall < delay) {  
      return;  
    }  
    lastCall = now;  
    context = this;  
    args = functionArgs;  
    return func.apply(context, args);  
  } as T;  
}

// 退出登录
function logout () {
	removeToken();
	store.commit('SET_MASTER_INFO', masterInfo);
	store.commit('SET_SERVICE_INFO', serviceInfo);
	store.commit('SET_ADDRESS_LIST', []);
	store.commit('SET_RESUME_DELIVER_COUNT', 0);
}

// 设置角色tabbar
function setTabBar(userRole: UserRole, state: any) {
	// 雇主tabbar
	const masterTabbar = [
		{
			index: 0,
			text: '首页',
			pagePath: "pages/index/index",
			iconPath: '/static/images/tabbar/index.png',
			selectedIconPath: '/static/images/tabbar/index-selected.png',
		},
		{
			index: 1,
			text: '全部服务',
			pagePath: 'pages/service/service/service',
			iconPath: '/static/images/tabbar/service.png',
			selectedIconPath: '/static/images/tabbar/service-selected.png',
		},
		{
			index: 2,
			text: '我的',
			pagePath: 'pages/my/my/my',
			iconPath: '/static/images/tabbar/my.png',
			selectedIconPath: '/static/images/tabbar/my-selected.png',
		},
	];
	// 家政工tabbar
	const serviceTabbar = [
		{
			index: 0,
			text: '找工作',
			pagePath: "pages/index/index",
			iconPath: '/static/images/tabbar/work.png',
			selectedIconPath: '/static/images/tabbar/work-selected.png',
		},
		{
			index: 1,
			text: '消息',
			pagePath: 'servicePages/message/message/message',
			iconPath: '/static/images/tabbar/message.png',
			selectedIconPath: '/static/images/tabbar/message-selected.png',
		},
		{
			index: 2,
			text: '我的',
			pagePath: 'servicePages/my/my/my',
			iconPath: '/static/images/tabbar/my-grey.png',
			selectedIconPath: '/static/images/tabbar/my-selected.png',
		},
	];
	
	const enterprisesId = state && state.master.masterInfo.enterprisesId;
	const enterprises = state && state.service.serviceInfo.enterprises;
	if (userRole === UserRole.Service && (enterprisesId || enterprises)) {
		serviceTabbar[0] = {
			index: 0,
			text: '服务打卡',
			pagePath: "pages/index/index",
			iconPath: '/static/images/tabbar/calendar.png',
			selectedIconPath: '/static/images/tabbar/calendar-selected.png',
		};
	}
	
	// 设置tabbar
	[...(userRole === UserRole.Service ? serviceTabbar : masterTabbar)].forEach(tabbar => {
		uni.setTabBarItem(tabbar);
	});
}

export {
	compareVersion,
	getSystemVersion,
	imgToBase64,
	base64ToFile,
	getSelectorData,
	throttle,
	logout,
	setTabBar,
}